package com.crowntit.infrastructure.adapter.port;

import com.alibaba.fastjson2.JSON;
import com.crowntit.domain.goods.adapter.port.IGroupBuyProductPort;
import com.crowntit.domain.goods.model.entity.GoodsConfigInfoEntity;
import com.crowntit.domain.goods.model.entity.QueryGoodsConfigEntity;
import com.crowntit.domain.order.model.entity.GroupBuyLockInfoEntity;
import com.crowntit.domain.order.model.entity.GroupBuyLockServiceReqEntity;
import com.crowntit.domain.order.model.entity.GroupBuySettlementInfoEntity;
import com.crowntit.domain.order.model.entity.GroupBuySettlementServiceReqEntity;
import com.crowntit.infrastructure.gateway.IGroupBuyMarketService;
import com.crowntit.infrastructure.gateway.dto.gbm.*;
import com.crowntit.types.enums.GroupBuyServiceResponseStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import retrofit2.Call;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class GroupBuyProductPort implements com.crowntit.domain.order.adapter.port.IGroupBuyMarketPort, IGroupBuyProductPort {

    @Value("${gbm.source}")
    private String source;
    @Value("${gbm.channel}")
    private String channel;

    @Resource
    private IGroupBuyMarketService groupBuyMarketService;

    @Override
    public GroupBuyLockInfoEntity lockMarketOrder(GroupBuyLockServiceReqEntity requestEntity) throws IOException {
        GroupBuyMarketLockRequestDTO groupBuyMarketLockRequestDTO = new GroupBuyMarketLockRequestDTO();
        groupBuyMarketLockRequestDTO.setUserId(requestEntity.getUserId());
        groupBuyMarketLockRequestDTO.setTeamId(requestEntity.getTeamId());
        groupBuyMarketLockRequestDTO.setActivityId(requestEntity.getActivityId());
        groupBuyMarketLockRequestDTO.setSource(source);
        groupBuyMarketLockRequestDTO.setChannel(channel);
        groupBuyMarketLockRequestDTO.setGoodsId(requestEntity.getProductId());
        groupBuyMarketLockRequestDTO.setOutTradeNo(requestEntity.getOutTradeNo());
//        groupBuyMarketLockRequestDTO.setNotifyUrl(requestEntity.getNotifyUrl());

        Call<Response<GroupBuyMarketLockResponseDTO>> call = groupBuyMarketService.lockMarketPayOrder(groupBuyMarketLockRequestDTO);
        Response<GroupBuyMarketLockResponseDTO> response = call.execute().body();
        log.info("团购锁单-响应出参: {}", response);

        assert response != null;
        String responseCode = response.getCode();
        if (responseCode.equals("0000")) {
            GroupBuyMarketLockResponseDTO responseData = response.getData();
            return GroupBuyLockInfoEntity.builder()
                    .isGroupBuy(1)
                    .deductionPrice(responseData.getDeductionPrice())
                    .payPrice(responseData.getPayPrice())
                    .gbmOutTradeNo(requestEntity.getOutTradeNo())
                    .groupBuyServiceResponseStatus("SUCCESS_LOCK")
                    .build();
        }

        return GroupBuyLockInfoEntity.builder()
                .groupBuyServiceResponseStatus("EXCEPTION_LOCK")
                .gbmOutTradeNo(requestEntity.getOutTradeNo())
                .deductionPrice(BigDecimal.ZERO)
                .isGroupBuy(1)
                .build();
    }

    @Override
    public GroupBuySettlementInfoEntity settlementMarketOrder(GroupBuySettlementServiceReqEntity requestEntity) throws IOException {
        log.info("团购交易结算-入参: {}", JSON.toJSONString(requestEntity));
        String userId = requestEntity.getUserId();
        String outTradeNo = requestEntity.getOutTradeNo();

        MarketTradeSettlementOrderRequestDTO requestDTO = new MarketTradeSettlementOrderRequestDTO();
        requestDTO.setSource(source);
        requestDTO.setChannel(channel);
        requestDTO.setOutTradeNo(outTradeNo);
        requestDTO.setUserId(userId);
        log.info("团购交易结算-外部接口入参: {}", JSON.toJSONString(requestDTO));
        Call<Response<MarketTradeSettlementOrderResponseDTO>> responseCall = groupBuyMarketService.settlementMarketTradeOrder(requestDTO);
        Response<MarketTradeSettlementOrderResponseDTO> body = responseCall.execute().body();
        log.info("团购交易结算-出参: {}", JSON.toJSONString(body));

        GroupBuySettlementInfoEntity groupBuySettlementInfoEntity = new GroupBuySettlementInfoEntity();

        if (body.getCode().equals("0000")) {
            log.info("团购交易结算-接口正常响应");
            groupBuySettlementInfoEntity.setGroupBuyServiceResponseStatus(GroupBuyServiceResponseStatusEnum.SUCCESS_PAY.getInfo());
        } else {
            log.info("团购交易结算-接口响应异常");
            groupBuySettlementInfoEntity.setGroupBuyServiceResponseStatus(GroupBuyServiceResponseStatusEnum.EXCEPTION_PAY.getInfo());
        }

        return groupBuySettlementInfoEntity;
    }

    @Override
    public GoodsConfigInfoEntity queryGoodsConfig(QueryGoodsConfigEntity queryGoodsEntity) throws IOException {
        log.info("查询商品团购配置");
        String userId = queryGoodsEntity.getUserId();
        String productId = queryGoodsEntity.getProductId();

        QueryProductConfigReqDTO requestDTO = QueryProductConfigReqDTO.builder()
                .goodsId(productId)
                .userId(userId)
                .source(source)
                .channel(channel)
                .build();
        log.info("团购交易结算-外部接口入参: {}", JSON.toJSONString(requestDTO));

        Call<Response<QueryProductConfigResDTO>> responseCall = groupBuyMarketService.queryGoodsConfig(requestDTO);
        Response<QueryProductConfigResDTO> body = responseCall.execute().body();
        log.info("团购交易结算-出参: {}", JSON.toJSONString(body));

        if (body.getCode().equals("0000")) {
            log.info("查询商品团购配置-接口正常响应");
            QueryProductConfigResDTO data = body.getData();
            List<QueryProductConfigResDTO.Team> groupBuyTeamListRes = data.getTeamList();
            QueryProductConfigResDTO.Goods goodsRes = data.getGoods();

            GoodsConfigInfoEntity.Goods goods = GoodsConfigInfoEntity.Goods.builder()
                    .goodsId(goodsRes.getGoodsId())
                    .goodsName(goodsRes.getGoodsName())
                    .activityId(goodsRes.getActivityId())
                    .originalPrice(goodsRes.getOriginalPrice())
                    .deductionPrice(goodsRes.getDeductionPrice())
                    .payPrice(goodsRes.getPayPrice())
                    .build();

            List<GoodsConfigInfoEntity.Team> groupBuyTeamList = new ArrayList<>();
            if (groupBuyTeamListRes != null && !groupBuyTeamListRes.isEmpty()){
                for (QueryProductConfigResDTO.Team groupBuyTeamListResItem : groupBuyTeamListRes) {
                    String teamId = groupBuyTeamListResItem.getTeamId();
                    Long activityId = groupBuyTeamListResItem.getActivityId();
                    String teamUserId = groupBuyTeamListResItem.getUserId();
                    Integer targetCount = groupBuyTeamListResItem.getTargetCount();
                    Integer lockCount = groupBuyTeamListResItem.getLockCount();
                    Integer completeCount = groupBuyTeamListResItem.getCompleteCount();
                    Date validStartTime = groupBuyTeamListResItem.getValidStartTime();
                    Date validEndTime = groupBuyTeamListResItem.getValidEndTime();
                    String validTimeCountdown = groupBuyTeamListResItem.getValidTimeCountdown();
                    String outTradeNo = groupBuyTeamListResItem.getOutTradeNo();

                    groupBuyTeamList.add(GoodsConfigInfoEntity.Team.builder()
                            .teamId(teamId)
                            .activityId(activityId)
                            .userId(teamUserId)
                            .targetCount(targetCount)
                            .lockCount(lockCount)
                            .completeCount(completeCount)
                            .validStartTime(validStartTime)
                            .validEndTime(validEndTime)
                            .validTimeCountdown(validTimeCountdown)
                            .outTradeNo(outTradeNo)
                            .build());
                }
            }

            return GoodsConfigInfoEntity.builder()
                    .groupBuyTeamList(groupBuyTeamList)
                    .goods(goods)
                    .isGroupBuyConfig(true)
                    .build();
        } else {
            log.info("查询商品团购配置-接口响应异常");
            return null;
        }
    }
}
